package com.zang.blogz.intercept;


import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.jwt.exception.SaJwtException;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;

import io.github.vampireachao.stream.core.optional.Opp;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author 臧臧 on 2022/6/17
 */
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    @Value("${sa-token.token-prefix}")
    private String tokenStartWith;

    @Value("${sa-token.token-name}")
    private String tokenHeader;
    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new SaRouteInterceptor((req, res, handler)->{

                    //后台管理员接口鉴权
            SaRouter.match("/blogz/*/admin/**", r -> {

                Opp<String> header = Opp.ofStr(req.getHeader(tokenHeader));
                if (header.isEmpty()){
                    throw new SaJwtException("当前令牌不存在,请先进行登录获得令牌");
                }


                if (!header.get().startsWith(tokenStartWith)) {

                    throw new SaJwtException("当前令牌不符合规定");
                }

                long timeout = StpUtil.getTokenTimeout();

                if (timeout == -2){

                    throw new SaJwtException("当前令牌已过期,请重新登录进行获取");
                }
                StpUtil.checkPermission(req.getRequestPath());});

            //评论需要登录后才可以
            SaRouter.match("**/login/**").match(SaHttpMethod.POST).check(r -> StpUtil.checkLogin());

        })).addPathPatterns("/**")

                .excludePathPatterns("/blogz/login/**")
                .excludePathPatterns("/doc.html")
                .excludePathPatterns("/blogz/register/**");


    }

}
